<template>
  <view class="signature-container">
    <view class="canvas-wrapper">
      <canvas
        :canvas-id="canvasId"
        :id="canvasId"
        type="2d"
        class="signature-pad"
        disable-scroll="true"
        @touchstart="touchStart"
        @touchmove="touchMove"
        @touchend="touchEnd"
      ></canvas>
    </view>

    <!-- 添加按钮组 -->
    <view class="button-group">
      <button class="btn cancel" @tap="handleCancel">取消</button>
      <button class="btn clear" @tap="clearCanvas">
        <text class="iconfont">重写</text>
      </button>
      <button class="btn confirm" @tap="handleConfirm">确认</button>
    </view>
  </view>
</template>

<script>
import global from "@/plugins/global";
export default {
  data() {
    return {
      canvasId: "signature-pad",
      context: null,
      canvas: null,
      canvasWidth: 300,
      canvasHeight: 200,
      isDrawing: false,
      lastPoint: null,
      pageParams: {},
    };
  },

  onLoad(options) {
    this.pageParams = options;
    console.log("Received parameters:", options);
    // 获取上一个页面传来的参数
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on("acceptDataFromOpenerPage", (data) => {
      console.error("Received data from opener:", data);
      // 保存接收到的数据
      this.pageParams = {
        ...this.pageParams,
        ...data,
      };
    });
  },
  unmounted() {
    uni.$off('acceptDataFromOpenerPage');
  },

  async mounted() {
    try {
      const systemInfo = uni.getSystemInfoSync();
      this.canvasWidth = systemInfo.windowWidth;
      this.canvasHeight = systemInfo.windowHeight - uni.upx2px(140);

      await this.$nextTick();
      await this.initCanvas();
    } catch (error) {
      console.error("mounted error:", error);
    }
  },

  methods: {
    async initCanvas() {
      try {
        console.log("Platform:", process.env.VUE_APP_PLATFORM);
        console.log("Canvas ID:", this.canvasId);

        // #ifdef MP-TOUTIAO || MP-LARK
        // 字节系小程序使用 createCanvasContext
        this.context = uni.createCanvasContext(this.canvasId, this);

        // 设置画布尺寸
        this.context.width = this.canvasWidth;
        this.context.height = this.canvasHeight;

        // 添加白色背景
        this.context.fillStyle = '#ffffff';  // 设置填充颜色为白色
        this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight);  // 填充整个画布

        // 设置基础画笔样式
        this.context.setStrokeStyle("#000000");
        this.context.setLineWidth(8);
        this.context.setLineCap("round");
        this.context.setLineJoin("round");

        // 应用设置
        await new Promise((resolve) => this.context.draw(false, resolve));
        console.log("Context initialized:", this.context);
        // #endif

        // #ifndef MP-TOUTIAO || MP-LARK
        // 其他平台的处理方式...
        // #endif
      } catch (error) {
        console.error("initCanvas error:", error);
        console.error("Error details:", error.message);
      }
    },

    touchStart(e) {
      if (!this.context) {
        console.error("Canvas context not initialized");
        return;
      }

      const touch = e.touches[0];
      this.isDrawing = true;
      this.lastPoint = {
        x: touch.x,
        y: touch.y,
      };

      // #ifdef MP-TOUTIAO || MP-LARK
      this.context.beginPath();
      this.context.moveTo(touch.x, touch.y);
      this.context.draw(true);
      // #endif
    },

    touchMove(e) {
      if (!this.isDrawing || !this.context) return;

      const touch = e.touches[0];

      // #ifdef MP-TOUTIAO || MP-LARK
      this.context.moveTo(this.lastPoint.x, this.lastPoint.y);
      this.context.lineTo(touch.x, touch.y);
      this.context.stroke();
      this.context.draw(true);
      // #endif

      this.lastPoint = {
        x: touch.x,
        y: touch.y,
      };
    },

    touchEnd() {
      this.isDrawing = false;
    },

    clearCanvas() {
      if (!this.context) return;

      // #ifdef MP-TOUTIAO || MP-LARK
      // 清空整个画布并重新填充白色背景
      this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.context.fillStyle = '#ffffff';
      this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight);

      // 重置画笔样式
      this.context.setStrokeStyle("#000000");
      this.context.setLineWidth(8);
      this.context.setLineCap("round");
      this.context.setLineJoin("round");
      
      // 应用更改
      this.context.draw();
      // #endif
    },

    rewrite() {
      if (this.signaturePad) {
        this.signaturePad.clear(); // 完全清空画布
      }
    },
    disablePageScroll() {
      // 禁用页面滚动
      document.body.style.overflow = "hidden";
      document.body.ontouchmove = function () {
        return false;
      };
    },
    enablePageScroll() {
      // 恢复页面滚动
      document.body.style.overflow = "";
      document.body.ontouchmove = null;
    },
    handleCancel() {
      // 返回上一页
      uni.navigateBack();
    },
    handleConfirm() {
      // #ifdef MP-TOUTIAO || MP-LARK
      uni.showLoading({
        title: "保存中...",
      });

      uni.canvasToTempFilePath(
        {
          canvasId: this.canvasId,
          fileType: "jpg",
          quality: 0.8,
          destWidth: this.canvasWidth * 2,
          destHeight: this.canvasHeight * 2,
          backgroundColor: "#ffffff",
          success: (res) => {
            const filePath = res.tempFilePath;
            let token = uni.getStorageSync("token");

            uni.uploadFile({
              url: global.BACKEND_URL + "/extension/file/upload",
              fileType: "image",
              filePath: filePath,
              name: "file",
              header: {
                Authorization: "Bearer " + token,
                "Content-Type": "multipart/form-data",
                TenantId: 0,
              },
              success: (uploadRes) => {
                const data = JSON.parse(uploadRes.data).data[0];
                // 返回上一页并传递数据
                uni.navigateBack({
                  delta: 1,
                  success: () => {
                    console.log("签名完成",this.pageParams.signType);
                    // 使用一次性事件监听器，确保数据只发送一次
                    uni.$emit(this.pageParams.signType, {
                      fileInfo: data,
                      prevPageParma: this.pageParams.prevPageParma,
                      success: true
                    });
                    console.log("签名完成");
                  },
                });
                uni.showToast({
                  title: "保存成功",
                  icon: "success",
                });
              },
              fail: (err) => {
                console.error("Upload failed:", err);
                uni.showToast({
                  title: "保存失败",
                  icon: "error",
                });
              },
              complete: () => {
                uni.hideLoading();
              },
            });
          },
          fail: (err) => {
            console.error("Canvas to temp file failed:", err);
            uni.hideLoading();
            uni.showToast({
              title: "保存失败",
              icon: "error",
            });
          },
        },
        this
      );
      // #endif
    },
  },
};
</script>

<style scoped>
.signature-container {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.canvas-wrapper {
  flex: 1;
  width: 100%;
  position: relative;
  margin-bottom: 140rpx;
}

.signature-pad {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #fff;
}

.signature-header {
  padding: 30rpx;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 16rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #666;
}

.button-group {
  height: 120rpx;
  padding: 0 32rpx calc(20rpx + env(safe-area-inset-bottom));
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20rpx;
  background: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  box-shadow: 0 -1rpx 0 0 rgba(0, 0, 0, 0.1);
}

.btn {
  flex: 1;
  height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  font-weight: 400;
}

.btn:active {
  opacity: 0.8;
}

.clear {
  background-color: #ffffff;
  color: #333333;
  border: 2rpx solid #e5e5e5;
}

.clear .iconfont {
  margin-right: 8rpx;
  font-size: 28rpx;
}

.cancel {
  background-color: #ffffff;
  color: #333333;
  border: 2rpx solid #e5e5e5;
}

.confirm {
  background-color: #11acf1;
  color: #ffffff;
}

.confirm:hover {
  background-color: #0e9bd8;
}
</style>